<template>
  <div class="chat-layout">
    <!-- 加载状态遮罩 -->
    <div v-if="isInitializing" class="loading-overlay">
      <div class="loading-spinner">
        <div class="spinner"></div>
        <p>正在加载对话记录...</p>
      </div>
    </div>
    
    <!-- 错误提示 -->
    <div v-if="lastError" class="error-toast" @click="clearError">
      <div class="error-content">
        <svg class="error-icon" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
          <circle cx="12" cy="12" r="10"/>
          <line x1="15" y1="9" x2="9" y2="15"/>
          <line x1="9" y1="9" x2="15" y2="15"/>
        </svg>
        <span>{{ lastError.message }}</span>
        <button class="close-btn">×</button>
      </div>
    </div>
    
    <aside class="sidebar" :class="{ collapsed: sidebarCollapsed }">
      <div class="sidebar-header">
        <button class="toggle-btn" @click="toggleSidebar" :title="sidebarCollapsed ? '展开侧边栏' : '收起侧边栏'">
          <svg v-if="sidebarCollapsed" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
            <path d="M9 18l6-6-6-6"/>
          </svg>
          <svg v-else width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
            <path d="M15 18l-6-6 6-6"/>
          </svg>
        </button>
        <h3 v-show="!sidebarCollapsed">会话</h3>
        <button class="new-btn" v-show="!sidebarCollapsed"
                @click="onNewConversation">新建</button>
      </div>
      
      <!-- 会话列表加载状态 -->
      <div v-if="isInitializing && conversations.length === 0" class="conv-loading" v-show="!sidebarCollapsed">
        <div class="conv-loading-item">
          <div class="loading-placeholder title"></div>
          <div class="loading-placeholder meta"></div>
        </div>
        <div class="conv-loading-item">
          <div class="loading-placeholder title"></div>
          <div class="loading-placeholder meta"></div>
        </div>
      </div>
      
      <ul class="conv-list" v-show="!sidebarCollapsed" v-else>
        <li v-for="conv in conversations"
            :key="conv.id"
            :class="{ active: conv.id === currentConversationId }"
            @click="onSwitch(conv.id)">
          <div class="conv-title">{{ conv.title }}</div>
          <div class="conv-meta">{{ conv.lastMessage || '暂无消息' }}</div>
          <div class="conv-actions">
            <button class="rename"
                    @click.stop="onRename(conv)">重命名</button>
            <button class="delete"
                    @click.stop="onDelete(conv.id)">删除</button>
          </div>
        </li>
      </ul>
    </aside>
    <div class="chat-window">
      <div class="messages"
           ref="listRef">
        <MessageItem v-for="(msg, idx) in messages"
                     :key="msg.id || idx"
                     :message="msg"
                     @retry="onRetry" />
      </div>
      <InputBox :sending="sending"
                :isThinking="isThinking"
                :hasError="!!lastError"
                :retryCount="retryCount"
                @send="onSend"
                @abort="onAbort" />
    </div>
  </div>
</template>

<script setup>
import { onMounted, ref, nextTick, watch } from 'vue';
import MessageItem from './MessageItem.vue';
import InputBox from './InputBox.vue';
import { useChat } from '../../composables/useChat';

// 组合式：聊天逻辑 + 会话管理
const { 
  messages, 
  sending, 
  send, 
  connect, 
  conversations, 
  currentConversationId, 
  createNewConversation, 
  switchConversation, 
  renameConversation, 
  deleteConversation, 
  retryMessage,
  abortChat,
  isThinking,
  isInitializing,
  initializeChatData,
  lastError,
  clearError,
  retryCount
} = useChat();
const listRef = ref(null);

// 侧边栏展开收起状态
const sidebarCollapsed = ref(false);

/**
 * 切换侧边栏展开收起状态
 */
function toggleSidebar() {
  sidebarCollapsed.value = !sidebarCollapsed.value;
}

/**
 * 发送消息事件处理
 * @param {string} text - 用户输入文本
 */
function onSend(text) {
  send(text);
}

/**
 * 重试消息事件处理
 * @param {string} id - 需要重试的消息ID
 */
function onRetry(id) {
  retryMessage(id);
}

/**
 * 中断对话事件处理
 */
function onAbort() {
  abortChat();
}

// 会话管理事件
/**
 * 新建会话
 */
function onNewConversation() {
  createNewConversation('新对话');
}

/**
 * 切换会话
 * @param {string} id - 会话ID
 */
function onSwitch(id) {
  switchConversation(id);
}

/**
 * 重命名会话
 * @param {{id:string,title:string}} conv - 会话对象
 */
function onRename(conv) {
  const title = window.prompt('输入新的会话标题', conv.title || '新对话');
  if (title) renameConversation(conv.id, title);
}

/**
 * 删除会话
 * @param {string} id - 会话ID
 */
function onDelete(id) {
  deleteConversation(id);
}

// 自动滚动到最新
function scrollToBottom() {
  nextTick(() => {
    const el = listRef.value;
    if (el) el.scrollTop = el.scrollHeight;
  });
}

// 监听消息变化，自动滚动到最新
watch(messages, () => {
  scrollToBottom();
}, { deep: true });

onMounted(async () => {
  // 首先初始化聊天数据（从存储恢复）
  await initializeChatData();
  // 然后建立SSE连接
  await connect();
});
</script>

<style scoped>
.chat-layout {
  display: flex;
  height: 100vh;
  background: linear-gradient(135deg, #f0f8ff 0%, #e6f3ff 100%);
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
}

.sidebar {
  width: 320px;
  border-right: 1px solid rgba(59, 130, 246, 0.1);
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  display: flex;
  flex-direction: column;
  box-shadow: 4px 0 20px rgba(59, 130, 246, 0.08);
  transition: width 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.sidebar.collapsed {
  width: 60px;
}

.sidebar-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20px 24px;
  border-bottom: 1px solid rgba(59, 130, 246, 0.1);
  background: linear-gradient(135deg, #3b82f6 0%, #60a5fa 100%);
  color: white;
  position: relative;
}

.sidebar.collapsed .sidebar-header {
  justify-content: center;
  padding: 20px 12px;
}

.toggle-btn {
  background: rgba(255, 255, 255, 0.2);
  color: white;
  border: 1px solid rgba(255, 255, 255, 0.3);
  padding: 8px;
  border-radius: 8px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  backdrop-filter: blur(10px);
  position: absolute;
  left: 12px;
  top: 50%;
  transform: translateY(-50%);
}

.sidebar.collapsed .toggle-btn {
  position: static;
  transform: none;
}

.toggle-btn:hover {
  background: rgba(255, 255, 255, 0.3);
  border-color: rgba(255, 255, 255, 0.5);
  transform: translateY(-50%) scale(1.05);
}

.sidebar.collapsed .toggle-btn:hover {
  transform: scale(1.05);
}

.sidebar-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  letter-spacing: 0.5px;
  margin-left: 40px;
}

.new-btn {
  background: rgba(255, 255, 255, 0.2);
  color: white;
  border: 1px solid rgba(255, 255, 255, 0.3);
  padding: 8px 16px;
  border-radius: 12px;
  cursor: pointer;
  font-weight: 500;
  font-size: 14px;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  backdrop-filter: blur(10px);
}

.new-btn:hover {
  background: rgba(255, 255, 255, 0.3);
  border-color: rgba(255, 255, 255, 0.5);
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.conv-list {
  list-style: none;
  margin: 0;
  padding: 12px;
  overflow-y: auto;
  flex: 1;
}

.conv-list::-webkit-scrollbar {
  width: 6px;
}

.conv-list::-webkit-scrollbar-track {
  background: transparent;
}

.conv-list::-webkit-scrollbar-thumb {
  background: rgba(59, 130, 246, 0.2);
  border-radius: 3px;
}

.conv-list::-webkit-scrollbar-thumb:hover {
  background: rgba(59, 130, 246, 0.3);
}

.conv-list li {
  padding: 16px;
  margin-bottom: 8px;
  border-radius: 12px;
  cursor: pointer;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  background: rgba(255, 255, 255, 0.6);
  border: 1px solid rgba(59, 130, 246, 0.1);
  position: relative;
  overflow: hidden;
}

.conv-list li::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(135deg, rgba(59, 130, 246, 0.05) 0%, rgba(147, 197, 253, 0.05) 100%);
  opacity: 0;
  transition: opacity 0.3s ease;
}

.conv-list li:hover::before {
  opacity: 1;
}

.conv-list li:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(59, 130, 246, 0.15);
  border-color: rgba(59, 130, 246, 0.2);
}

.conv-list li.active {
  background: linear-gradient(135deg, #3b82f6 0%, #60a5fa 100%);
  color: white;
  border-color: #3b82f6;
  box-shadow: 0 8px 25px rgba(59, 130, 246, 0.3);
}

.conv-list li.active::before {
  display: none;
}

.conv-title {
  font-weight: 600;
  font-size: 15px;
  margin-bottom: 6px;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 1;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.conv-meta {
  font-size: 13px;
  opacity: 0.7;
  line-height: 1.3;
  margin-bottom: 12px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.conv-actions {
  opacity: 0;
  transition: opacity 0.2s ease;
  display: flex;
  gap: 8px;
  position: relative;
  z-index: 1;
}

.conv-list li:hover .conv-actions {
  opacity: 1;
}

.conv-list li.active .conv-actions {
  opacity: 1;
}

.conv-actions .rename,
.conv-actions .delete {
  background: rgba(255, 255, 255, 0.1);
  border: 1px solid rgba(59, 130, 246, 0.2);
  padding: 6px 12px;
  border-radius: 8px;
  cursor: pointer;
  font-size: 12px;
  font-weight: 500;
  transition: all 0.2s ease;
  color: #3b82f6;
}

.conv-list li.active .conv-actions .rename,
.conv-list li.active .conv-actions .delete {
  background: rgba(255, 255, 255, 0.2);
  border-color: rgba(255, 255, 255, 0.3);
  color: white;
}

.conv-actions .rename:hover {
  background: rgba(59, 130, 246, 0.1);
  border-color: #3b82f6;
}

.conv-actions .delete {
  color: #ef4444;
  border-color: rgba(239, 68, 68, 0.2);
}

.conv-actions .delete:hover {
  background: rgba(239, 68, 68, 0.1);
  border-color: #ef4444;
}

.conv-list li.active .conv-actions .delete:hover {
  background: rgba(239, 68, 68, 0.2);
  color: #fecaca;
}

.chat-window {
  flex: 1;
  display: flex;
  flex-direction: column;
  height: 100vh;
  max-width: 900px;
  margin: 0 auto;
  background: transparent;
  position: relative;
}

.messages {
  flex: 1;
  overflow-y: auto;
  padding: 24px;
  background: transparent;
}

.messages::-webkit-scrollbar {
  width: 8px;
}

.messages::-webkit-scrollbar-track {
  background: transparent;
}

.messages::-webkit-scrollbar-thumb {
  background: rgba(59, 130, 246, 0.2);
  border-radius: 4px;
}

.messages::-webkit-scrollbar-thumb:hover {
  background: rgba(59, 130, 246, 0.3);
}

/* 加载状态样式 */
.loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(240, 248, 255, 0.95);
  backdrop-filter: blur(5px);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.loading-spinner {
  text-align: center;
  color: #3b82f6;
}

.spinner {
  width: 40px;
  height: 40px;
  border: 3px solid rgba(59, 130, 246, 0.1);
  border-top: 3px solid #3b82f6;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin: 0 auto 16px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.loading-spinner p {
  margin: 0;
  font-size: 14px;
  font-weight: 500;
}

/* 错误提示样式 */
.error-toast {
  position: fixed;
  top: 20px;
  right: 20px;
  background: #fee2e2;
  border: 1px solid #fecaca;
  border-radius: 12px;
  padding: 0;
  z-index: 1001;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 4px 12px rgba(239, 68, 68, 0.15);
}

.error-toast:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(239, 68, 68, 0.2);
}

.error-content {
  display: flex;
  align-items: center;
  padding: 12px 16px;
  color: #dc2626;
  font-size: 14px;
  gap: 8px;
}

.error-icon {
  flex-shrink: 0;
}

.close-btn {
  background: none;
  border: none;
  color: #dc2626;
  font-size: 18px;
  cursor: pointer;
  padding: 0;
  margin-left: 8px;
  width: 20px;
  height: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  transition: background-color 0.2s;
}

.close-btn:hover {
  background: rgba(220, 38, 38, 0.1);
}

/* 会话列表加载占位符 */
.conv-loading {
  padding: 12px;
}

.conv-loading-item {
  padding: 16px;
  margin-bottom: 8px;
  border-radius: 12px;
  background: rgba(255, 255, 255, 0.6);
  border: 1px solid rgba(59, 130, 246, 0.1);
}

.loading-placeholder {
  background: linear-gradient(90deg, rgba(59, 130, 246, 0.1) 0%, rgba(59, 130, 246, 0.2) 50%, rgba(59, 130, 246, 0.1) 100%);
  background-size: 200% 100%;
  animation: shimmer 1.5s infinite;
  border-radius: 4px;
  height: 16px;
}

.loading-placeholder.title {
  width: 70%;
  margin-bottom: 8px;
}

.loading-placeholder.meta {
  width: 90%;
  height: 12px;
}

@keyframes shimmer {
  0% { background-position: -200% 0; }
  100% { background-position: 200% 0; }
}
@media (max-width: 768px) {
  .sidebar {
    width: 280px;
  }
  
  .sidebar.collapsed {
    width: 50px;
  }
  
  .sidebar-header {
    padding: 16px 20px;
  }
  
  .sidebar.collapsed .sidebar-header {
    padding: 16px 8px;
  }
  
  .conv-list {
    padding: 8px;
  }
  
  .conv-list li {
    padding: 12px;
  }
  
  .messages {
    padding: 16px;
  }
}

@media (max-width: 480px) {
  .chat-layout {
    flex-direction: column;
  }
  
  .sidebar {
    width: 100%;
    height: 200px;
    border-right: none;
    border-bottom: 1px solid rgba(59, 130, 246, 0.1);
  }
  
  .sidebar.collapsed {
    height: 60px;
    width: 100%;
  }
  
  .conv-list {
    flex-direction: row;
    overflow-x: auto;
    overflow-y: hidden;
  }
  
  .conv-list li {
    min-width: 200px;
    margin-right: 8px;
    margin-bottom: 0;
  }
}
</style>